package seentao.stdev.mobile.log.aop;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

@Component
public aspect MethodCalledLogAspect {
	
	@Resource
	private HttpServletRequest request;

	pointcut writeLog(): execution(public * seentao.stdev.mobile..*Controller.*(..));
	pointcut writeLog(): execution(public * seentao.stdev.mobile..*Service.*(..));
	pointcut writeLog(): execution(public * seentao.stdev.mobile..*DAO.*(..));

	before(): writeLog() {
		Class<?> target = thisJoinPoint.getTarget().getClass();
		String className = target.getName();
		String method = "Method: " + thisJoinPoint.getSignature().toLongString();
		String uri    = "URI:    " + request.getRequestURI();
		Object[] args = thisJoinPoint.getArgs();
		if (className.endsWith("Controller")) {
			writeLog(target, uri, null, "Accs");
			writeLog(target, method, args, "Accs");
		} else if (className.endsWith("Service")) {
			writeLog(target, method, args, "Serv");
		} else if (className.endsWith("DAO")) {
			Class<?>[] intf = target.getInterfaces();
			target = (intf!=null && intf.length>0) ? intf[0] : target;
			writeLog(target, method, args, "DAO ");
		}
	}

	/*after(): writeAccessExLog() {
		Class<?> target = thisJoinPoint.getTarget().getClass();
		String method = thisJoinPoint.getSignature().toShortString();
		String message = "Access exception in: " + method + ". Cause: ";
		writeLog(target, message, ex);
	}*/

	//=======================================
	
	private void writeLog(Class<?> target, String message, Object[] args, String prefix) {
		Logger log = Logger.getLogger(target);
		log.debug(prefix + " -> " + message);
		if (args != null && args.length > 0) {
			for (Object arg : args) {
				log.debug(prefix + " -> Param:  " + arg);
			}
		}
	}
	
	private void writeLog(Class<?> target, String message, Throwable t) {
		Logger log = Logger.getLogger(target);
		log.error(message + t.getMessage());
	}
}
